package com.dries.portal.module.pay.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dries.common.api.CommonResult;
import com.dries.portal.module.pay.config.WxPayProperties;
import com.dries.portal.module.pay.entity.CashDraws;
import com.dries.portal.module.pay.form.TransferForm;
import com.dries.portal.module.pay.mapper.CashDrawsMapper;
import com.dries.portal.module.pay.service.ICashDrawsService;
import com.ijpay.core.enums.SignType;
import com.ijpay.core.kit.WxPayKit;
import com.ijpay.wxpay.WxPayApi;
import com.ijpay.wxpay.model.GetTransferInfoModel;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Map;

@Service
public class CashDrawsServiceImpl extends ServiceImpl<CashDrawsMapper, CashDraws> implements ICashDrawsService {

    @Resource
    private WxPayProperties payProperties;

    @Override
    public Boolean saveTransfer(TransferForm form) {

        CashDraws cashDraws = new CashDraws();
        BeanUtils.copyProperties(form, cashDraws);

        cashDraws.setMoney(new BigDecimal(form.getMoney()));
        cashDraws.setCashNo(IdUtil.simpleUUID());
        cashDraws.setCashStatus(0);

        int insert = baseMapper.insert(cashDraws);
        return insert == 1;

    }

    @Override
    public CommonResult getCashDrawsInfo(CashDraws cashDraws) {
        try {
            // WxPayApiConfig wxPayApiConfig = WxPayApiConfigKit.getWxPayApiConfig();
            Map<String, String> params = GetTransferInfoModel.builder()
                    .nonce_str(WxPayKit.generateStr())
                    .partner_trade_no(cashDraws.getTradeNo())
                    .mch_id(payProperties.getConfig().getMchId())
                    .appid(payProperties.getConfig().getAppId())
                    .build()
                    .createSign(payProperties.getConfig().getPartnerKey(), SignType.MD5, false);

            String transferInfo = WxPayApi.getTransferInfo(params, payProperties.getConfig().getCertPath(), payProperties.getConfig().getMchId());
            Map<String, String> map = WxPayKit.xmlToMap(transferInfo);
            return CommonResult.success(map);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return CommonResult.failed("暂无提现记录");
    }

}